package com.codefarmer.practice.utile;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @description : HTTP请求
 * @author: codefarmer_z
 * @create: 2021-04-10 09:29
 */
@Component
@Slf4j
public class HttpsSend {

    /**   http  post请求 无token
     * @param url
     * @param param
     * @return
     */
    public static String sendPost(String url, String param) throws Exception {
        log.info("请求监管post接口 :url={}, param:{}", url, param);
        HttpResponse response = HttpRequest
                .post(url)
                .body(param)
                .execute();
        // 获取 http 返回值
        int status = response.getStatus();
        String responseBody = response.body();
        log.info("第三方推送接口响应, body:{}", responseBody);
//        if (!response.isOk()) {
//            log.error("第三方调用失败,statusCode:" + status + "body:" + responseBody);
//            throw new RRException ("http返回失败");
//        }
        return responseBody;
    }

    /**
     *  get 请求
     * @param url 地址
     * @param paramMap 参数
     * @param headers
     * @param token token
     * @return
     * @throws Exception
     */
    public static String getSend(String url, Map<String, Object> paramMap, Map<String, String> headers, String token) throws Exception {

        log.info("第三方接口请求:url={}, param:{}", url, paramMap);
        HttpRequest httpRequest = HttpRequest.get(url);
        if (headers != null && headers.size() > 0) {
            log.info("第三方接口请求:headers={}", headers);
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpRequest.header(header.getKey(), header.getValue());
            }
        }
        if (paramMap != null && paramMap.size() > 0) {
            httpRequest.form(paramMap);
        }
        HttpResponse response = null;
        if (token != null) {
            response = httpRequest
                    .header("Authorization", "Bearer " + token)
                    .execute();
        } else {
            response = httpRequest
                    .execute();
        }
        String responseBody = response.body();
        log.info("第三方接口响应, body:{}", responseBody);
//        if (!response.isOk()) {
//            int status = response.getStatus();
//            log.error("第三方接口请求失败,statusCode:{}, body:{}", status, responseBody);
//            throw new RRException(responseBody);
//        }
        return responseBody;
    }


}
